﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using HRProject.Code.Common;
using HRProject.Code.DTO;
using HRProject.Code.DAO;

namespace HRProject
{
    public partial class DownloadFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string token = Request.Params["dfile"];
            DownloadableFileDAO downloadFileDao = new DownloadableFileDAO();
            BLDownloadableFile file = downloadFileDao.Get(token);
            if (file == null)
            {
                Util.Alert(Response, ContentProvider.GetMessage("FileNotFound"));
                return;
            }
            string originalFile = Server.MapPath(file.Url);
            if (!File.Exists(originalFile))
            {
                Util.Alert(Response, ContentProvider.GetMessage("FileNotFound"));
                return;
            }
            FileStream fs = new FileStream(originalFile, FileMode.Open);

            Response.Clear();
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment; filename="
                + file.FileName);
            byte[] buffer = new byte[1000000];
            int count = fs.Read(buffer, 0, 1000000);
            MemoryStream ms = new MemoryStream(buffer, 0, count);
            Response.AppendHeader("Content-Length", Convert.ToString(count));
            ms.WriteTo(Response.OutputStream);
            ms.Flush();
            ms.Close();
            fs.Flush();
            fs.Close();
            buffer = null;
            Response.End();
        }
    }
}
